﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcShop.Extensions;

namespace MvcShop.MVC.Filters
{
    /// <summary>
    /// 页缓存Filter
    /// </summary>
    public class ShopCacheAttribute:ActionFilterAttribute
    {
        private TimeSpan _cacheDuration;

        /// <summary>
        /// 缓存时间 秒
        /// </summary>
        public int Duration { get; set; }

        public ShopCacheAttribute()
        {
            if(this.Duration==0)
            {
                this.Duration = 1800;
            }
            this._cacheDuration = TimeSpan.FromSeconds(Duration);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Duration <= 0) return;

            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;
            string eTag = request.Headers["If-Modified-Since"];

            if (eTag != null && TimeSpan.FromTicks(DateTime.Now.Ticks - DateTime.Parse(eTag).Ticks).Seconds > 0)
            {
                response.StatusCode = 304;
                response.StatusDescription = "Not Modified";
            }
            else
            {
                response.Cache.SetETag(DateTime.Now.Ticks.ToString());//设置HTTP 标头为指定的字符串
                HttpContextExtension.CacheResponseFor(filterContext.HttpContext, _cacheDuration);
            }
        }

       
    }
}
